import Table from './Table'

export default class Db {
    constructor (config) {
        this.db = openDatabase(config.name, config.version || '1.0', config.description|| '',config.size || 2 * 1024 * 1024)
        this.config = config
        if (config.dev) {
            this.db.transaction((tx)=>{
                if (config.tables instanceof Array) {
                    for (let table of config.tables) {
                        tx.executeSql('DROP TABLE ' + table.name)
                    }
                }else {
                    throw 'tables参数类型为数组'
                }
            })
        }

        this.tables = new Map()
        if ( config.tables ) {
            if (config.tables instanceof Array) {
                for (let table of config.tables) {
                    this.tables.set(table.name,table)
                }
            }else {
                throw 'tables参数类型为数组'
            }
        }
    }
    static i (config) {
        if (this.instance) {
            return this.instance
        }
        return new Db(config)
    }
    table ( name ) {
        return new Table(this.db, name, this.tables.get(name))
    }
}